<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 <title>Mantenimiento de unidad de medidas</title>
 <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/estilos.css" media="screen" />
 
 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <style>
    .cell-title {
      font-weight: bold;
    }

    .cell-effort-driven {
      text-align: center;
    }

    .cell-selection {
      border-right-color: silver;
      border-right-style: solid;
      background: #f5f5f5;
      color: gray;
      text-align: right;
      font-size: 10px;
    }

    .slick-row.selected .cell-selection {
      background-color: transparent; /* show default selected row background */
    }
    
     
    label, input { display:block; }
    input.text { margin-bottom:12px; width:95%; padding: .4em; }
    fieldset { padding:0; border:0; margin-top:25px; } 
    
    div#users-contain { width: 350px; margin: 20px 0; }
    div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
    div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
    .ui-dialog .ui-state-error { padding: .3em; }
    .validateTips { border: 1px solid transparent; padding: 0.3em; }
    
    
  </style>

 
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/slick.pager.css" type="text/css"/> 
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/slick.columnpicker.css" type="text/css"/>
  
  
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/slick.grid.css" type="text/css"/>
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/jquery-ui-1.8.16.custom.css" type="text/css"/>
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/examples.css" type="text/css"/>
  
  
<script src="${pageContext.request.contextPath}/js/jquery-1.7.min.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery.event.drag-2.2.js"></script> 
<script src="${pageContext.request.contextPath}/js/slick.core.js"></script>
<script src="${pageContext.request.contextPath}/js/slick.grid.js"></script>
 
<script src="${pageContext.request.contextPath}/js/firebugx.js"></script> 
<script src="${pageContext.request.contextPath}/js/jquery-ui-1.8.16.custom.min.js"></script>   
<script src="${pageContext.request.contextPath}/js/slick.formatters.js"></script>
<script src="${pageContext.request.contextPath}/js/slick.editors.js"></script>
<script src="${pageContext.request.contextPath}/js/slick.rowselectionmodel.js"></script> 
<script src="${pageContext.request.contextPath}/js/slick.dataview.js"></script>
<script src="${pageContext.request.contextPath}/js/slick.pager.js"></script>
<script src="${pageContext.request.contextPath}/js/slick.columnpicker.js"></script>

<link rel="stylesheet" href="${pageContext.request.contextPath}/css/jquery-ui.css">
<script src="${pageContext.request.contextPath}/js/jquery-1.9.1.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery-ui.js"></script>
<script >
 
 

function modificar(vid,vdescripcion){ 
	 $( "#dialog-form-modificar" ).dialog( "open" ); 
	 document.getElementById("frmmodificar").id.value=vid; 
	 document.getElementById("frmmodificar").descripcion.value=vdescripcion; 
  
	 
}

 
 function eliminar(id){
	  document.getElementById("frmeliminar").action="${pageContext.request.contextPath}/unidadmedida/eliminar";
	  document.getElementById("frmeliminar").id.value=id;
	  document.getElementById("frmeliminar").submit();
 }
  
 var data = [];
 var datajson;
 var dataView;
 var grid;
 
 
 var contactDataProvider = function() {
	   //this sets up my data provider
	    this.init = function() {
	        $.ajax({
	            url: '${pageContext.request.contextPath}/unidadmedida/lista',
	            dataType: 'json',
	            async: false,
	            cache: false,
	            success: function(dataj) { 
	        			datajson=dataj; 
	            }
	    }); 
	};
};
  
 var columns = [
   {id: "id", name: "id", field: "id",    width: 15,minWidth: 15, editor: Slick.Editors.Text, sortable: true},  
   {id: "descripcion", name: "Descripcion", field: "descripcion", width: 180,minWidth: 120, editor: Slick.Editors.Text, sortable: true}, 
   {id: "edit", name: "", field: "",  formatter: linkFormatter = function ( row, cell, value, columnDef, dataContext ) {return "<a   href=\"javascript:modificar('"+dataContext['id']+"','"+dataContext['descripcion']+"')\"    ><img width=15 height=15 src=\"${pageContext.request.contextPath}/imagenes/edit.jpg\" ></a>";},width: 15,minWidth: 15, editor: Slick.Editors.Text, sortable: false},
   {id: "delete", name: "", field: "",  formatter: linkFormatter = function ( row, cell, value, columnDef, dataContext ) {return "<a href=\"javascript:eliminar('"+dataContext['id']+"')\"  onmouseover=\"window.status='';return true\" onmouseout=\"window.status='';return true\" ><img width=15 height=15 src=\"${pageContext.request.contextPath}/imagenes/delete.gif\" ></a>";},width: 15,minWidth: 15, editor: Slick.Editors.Text, sortable: false}
   
 ];

 var options = {
   editable: false,
   enableAddRow: false,
   enableCellNavigation: true,
   asyncEditorLoading: true,
   forceFitColumns: true,
   topPanelHeight: 25
 };

 var sortcol = "id";
 var sortdir = 1;
 var percentCompleteThreshold = 0;
 var searchString = "";
 

 function myFilter(item, args) {
   if (item["percentComplete"] < args.percentCompleteThreshold) {
     return false;
   }

   if (args.searchString != "" && item["descripcion"].indexOf(args.searchString) == -1) {
     return false;
   }

   return true;
 }

 function percentCompleteSort(a, b) {
   return a["percentComplete"] - b["percentComplete"];
 }

 function comparer(a, b) {
   var x = a[sortcol], y = b[sortcol];
   return (x == y ? 0 : (x > y ? 1 : -1));
 }

 function toggleFilterRow() {
   grid.setTopPanelVisibility(!grid.getOptions().showTopPanel);
 }

 

 $(function () {
	 
	 var cdo = new contactDataProvider();
	 cdo.init();
	  
	  // prepare the data
  for (var i = 0; i < datajson.length; i++) {
    var d = (data[i] = {});
     d["id"] = datajson[i].id; 
	 d["descripcion"] = datajson[i].descripcion; 
	 
  } 
	 
	 dataView = new Slick.Data.DataView({ inlineFilters: true });
	  grid = new Slick.Grid("#myGrid", dataView, columns, options);
	  grid.setSelectionModel(new Slick.RowSelectionModel());

	  var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
	  var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);


	  // move the filter panel defined in a hidden div into grid top panel
	  $("#inlineFilterPanel")
	      .appendTo(grid.getTopPanel())
	      .show(); 
	  
	  grid.onKeyDown.subscribe(function (e) { // select all rows on ctrl-a
	    if (e.which != 65 || !e.ctrlKey) {	
	      return false;
	    }

	    var rows = [];
	    for (var i = 0; i < dataView.getLength(); i++) {
	      rows.push(i);
	    }

	    grid.setSelectedRows(rows);
	    e.preventDefault();
	  });

	  grid.onSort.subscribe(function (e, args) {
	    sortdir = args.sortAsc ? 1 : -1;
	    sortcol = args.sortCol.field;

	    if ($.browser.msie && $.browser.version <= 8) {
	      // using temporary Object.prototype.toString override
	      // more limited and does lexicographic sort only by default, but can be much faster

	      var percentCompleteValueFn = function () {
	        var val = this["percentComplete"];
	        if (val < 10) {
	          return "00" + val;
	        } else if (val < 100) {
	          return "0" + val;
	        } else {
	          return val;
	        }
	      };

	      // use numeric sort of % and lexicographic for everything else
	      dataView.fastSort((sortcol == "percentComplete") ? percentCompleteValueFn : sortcol, args.sortAsc);
	    } else {
	      // using native sort with comparer
	      // preferred method but can be very slow in IE with huge datasets
	      dataView.sort(comparer, args.sortAsc);
	    }
	  });

	  // wire up model events to drive the grid
	  dataView.onRowCountChanged.subscribe(function (e, args) {
	    grid.updateRowCount();
	    grid.render();
	  });

	  dataView.onRowsChanged.subscribe(function (e, args) {
	    grid.invalidateRows(args.rows);
	    grid.render();
	  });

	  dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
	    var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
	    var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
	    var options = grid.getOptions();

	    if (options.enableAddRow != enableAddRow) {
	      grid.setOptions({enableAddRow: enableAddRow});
	    }
	  });


	  var h_runfilters = null;

	  // wire up the slider to apply the filter to the model
	  $("#pcSlider,#pcSlider2").slider({
	    "range": "min",
	    "slide": function (event, ui) {
	      Slick.GlobalEditorLock.cancelCurrentEdit();

	      if (percentCompleteThreshold != ui.value) {
	        window.clearTimeout(h_runfilters);
	        h_runfilters = window.setTimeout(updateFilter, 10);
	        percentCompleteThreshold = ui.value;
	      }
	    }
	  });


	  // wire up the search textbox to apply the filter to the model
	  $("#txtSearch,#txtSearch2").keyup(function (e) {
	    Slick.GlobalEditorLock.cancelCurrentEdit();

	    // clear on Esc
	    if (e.which == 27) {
	      this.value = "";
	    }

	    searchString = this.value;
	    updateFilter();
	  });

	  function updateFilter() {
	    dataView.setFilterArgs({
	      percentCompleteThreshold: percentCompleteThreshold,
	      searchString: searchString
	    });
	    dataView.refresh();
	  }

	  $("#btnSelectRows").click(function () {
	    if (!Slick.GlobalEditorLock.commitCurrentEdit()) {
	      return;
	    }

	    var rows = [];
	    for (var i = 0; i < 10 && i < dataView.getLength(); i++) {
	      rows.push(i);
	    }

	    grid.setSelectedRows(rows);
	  });


	  // initialize the model after all the events have been hooked up
	  dataView.beginUpdate();
	  dataView.setItems(data);
	  dataView.setFilterArgs({
	    percentCompleteThreshold: percentCompleteThreshold,
	    searchString: searchString
	  });
	  dataView.setFilter(myFilter);
	  dataView.endUpdate();

	  // if you don't want the items that are not visible (due to being filtered out
	  // or being on a different page) to stay selected, pass 'false' to the second arg
	  dataView.syncGridSelection(grid, true);

	  $("#gridContainer").resizable();
 
      var  
      frmnuevo_descripcion = $( "#frmnuevo_descripcion"), 
       
      frmmodificar_descripcion = $( "#frmmodificar_descripcion"),  
      
	  tips = $( ".validateTips");
	  
    function updateTips( t ) {
      tips .text( t ) .addClass( "ui-state-highlight" );
      setTimeout(function() {
       		 tips.removeClass( "ui-state-highlight", 1500 );
      	}, 500 );
    }
 
    function checkLength( o, n, min, max ) {
      if ( o.val().length > max || o.val().length < min ) {
        o.addClass( "ui-state-error" );
        updateTips( "Logitud de " + n + " debe estar entre " +
          min + " y " + max + "." );
        return false;
      } else {
        return true;
      }
    }
 
    function checkRegexp( o, regexp, n ) {
      if ( !( regexp.test( o.val() ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
      } else {
        return true;
      }
    }
 
    $( "#dialog-form" ).dialog({
      autoOpen: false,
      height: 250,
      width: 450,
      modal: true,
      buttons: {
        "Crear unidad de medida": function() {
        	 
        	
          var bValid = true;   
          bValid = bValid && checkLength( frmnuevo_descripcion, "descripcion", 3, 45 ); 
 
          if ( bValid ) {
        	  document.getElementById("frmnuevo").action="${pageContext.request.contextPath}/unidadmedida/nuevo";
        	  document.getElementById("frmnuevo").submit();
 
          }
        },
        "Cancelar": function() {
          $( this ).dialog( "close" );
        }
      },
      close: function() {
//         allFields.val( "" ).removeClass( "ui-state-error" );
      }
    });
    
    
    
    $( "#dialog-form-modificar" ).dialog({
        autoOpen: false,
        height: 250,
        width: 450,
        modal: true,
        buttons: {
          "Modificar unidad de medida": function() {
        	   
            var bValid = true;   
            bValid = bValid && checkLength(frmmodificar_descripcion, "descripcion", 3, 45 ); 
 
            if ( bValid ) {
          	  document.getElementById("frmmodificar").action="${pageContext.request.contextPath}/unidadmedida/modifica";
          	  document.getElementById("frmmodificar").submit();
 
            }
          },
          "Cancelar": function() {
            $( this ).dialog( "close" );
          }
        },
 
      });
 
    $( "#create-forma" )
      .button()
      .click(function() {
        $( "#dialog-form" ).dialog( "open" );
      });
    
    $( "#salir" )
    .button()
    .click(function() {
		location.href="${pageContext.request.contextPath}/welcome";
    });
    
     
    
  });
 
 

  </script>
	 
</head> 

 

<body  >

<jsp:include page="cabecera.jsp"></jsp:include> 
  <form:form id="frmeliminar"  method="POST"  >
  	<form:hidden path="id" id="id"  />
  </form:form>

<div id="dialog-form" title="Crear nueva unidad de medida">
  <p class="validateTips">Todos los campos son requeridos.</p>
  <form:form id="frmnuevo"  commandName="command" method="POST"  >
  <fieldset> 
    <label for="descripcion">Descripcion</label>
    <input type="text" name="descripcion" id="frmnuevo_descripcion" class="text ui-widget-content ui-corner-all"> 
      
  </fieldset>
  </form:form>
</div>


<div id="dialog-form-modificar" title="Modificar unidad de medida">
  <p class="validateTips">Todos los campos son requeridos.</p>
  <form:form id="frmmodificar"  method="POST"  >
  <fieldset>
  	<form:hidden path="id" id="id"   /> 
    <label for="descripcion">Descripcion</label>
    <input type="text" name="descripcion" id="frmmodificar_descripcion" class="text ui-widget-content ui-corner-all">
 
  </fieldset>
  </form:form>
</div>

 
<form:form method="POST" name="form" action="${pageContext.request.contextPath}/unidadmedida">
 
	<center><h2>Mantenimiento de unidades de medida</h2></center>
	<div   class="ventana_ovalada_manto" >
	<br/>
	<c:if test="${not empty messageerror}" > <div  class="messageerror"> ${messageerror}</div></c:if>
	<br/> 
 
  <div style="width:60%;margin-left: auto;margin-right: auto;">
    <div class="grid-header" style="width:100%">
      <label>Lista de unidades de medida</label>
      <span style="float:right" class="ui-icon ui-icon-search" title="Toggle search panel"
            onclick="toggleFilterRow()"></span>
    </div>
    <div id="myGrid" style="width:100%;height:300px;"></div>
    <div id="pager" style="width:100%;height:20px;"></div>
      <br/>
		<table style="width: 20px;" >
		<tr>
		<td> <div class="btn" id="create-forma" >Nuevo</div> </td>
		<td> <div class="btn" id="salir" >Salir</div> </td>
		</tr>
		</table>
  </div>
  
	<div id="inlineFilterPanel" style="display:none;background:#dddddd;padding:1px;color:black;">
	  			<table border="0" cellpadding="0" cellspacing="0" ><tr><td>Filtro por descripcion</td><td> <input type="text" id="txtSearch2"></td></tr></table> 
	 </div> 


	
	<img   src="${pageContext.request.contextPath}/imagenes/candado.gif	" style="position:right;left: 15;bottom:  15;" width="15" height="15" >
	</div>
	  
	
</form:form> 
</body>
</html>